<template>
  <div class="main">
    <div :id="cid" class="item"></div>
    <el-card class="item sub">
      <div v-for="o in 4" :key="o">
        {{'图标说明 ' + o }}
      </div>
    </el-card>
  </div>
</template>

<script>
import * as d3 from 'd3';
import 'd3-scale'
import 'd3-shape'
import 'd3-array'
import 'd3-selection'
import randomWords from 'random-words'

export default {
  name: "Occlusion",
  props:['cid','height'],
  computed:{
  },
  mounted() {
    const width = 1000;
    const height = this.height.slice(0, -2)
    const svg = d3.select(`#${this.cid}`).append('svg').attr("viewBox", [0, 0, width, height]);

    const n = 1000;
    svg.selectAll("text")
        .data(randomWords(n).sort(d3.ascending))
        .join("text")
        .text(d => d)
        .attr("x", () => (width * Math.random()) | 0)
        .attr("y", () => (height * Math.random()) | 0);

    // change the priority on mouseover
    svg.selectAll("text")
        .on("mouseover", function () {
          this.setAttribute("data-priority", 2);
          occlusion(svg);
        })
        .on("mouseout", function () {
          this.setAttribute("data-priority", 0);
          occlusion(svg);
        });

    function occlusion(svg, against = "text") {
      const texts = [];
      svg.selectAll(against).each((d, i, e) => {
        const bbox = e[i].getBoundingClientRect();
        texts.push({
          name: e[i].nodeName,
          priority: +e[i].getAttribute("data-priority"),
          node: e[i],
          text: d,
          bbox,
          x: bbox.x,
          y: bbox.y,
          width: bbox.width,
          height: bbox.height
        });
      });

      texts.sort((a, b) => d3.descending(a.priority, b.priority));

      const filled = [];
      function intersect(a, b) {
        return !(
            a.x + a.width < b.x ||
            b.x + b.width < a.x ||
            a.y + a.height < b.y ||
            b.y + b.height < a.y
        );
      }

      for (const d of texts) {
        const isOccluded = d.name === "text" && filled.some(function(e){
          intersect(d, e)
        });
        d3.select(d.node).classed("occluded", isOccluded);
        if (!isOccluded) filled.push(d);
      }

      return filled;
    }
  },
  methods:{

  }
}
</script>

<style scoped>
.main{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-end
}
.item{
  flex-grow:1;
  flex-shrink:1;
}
.sub{
  max-width: 300px;
  min-width: 200px;
  flex-grow:1;
  flex-shrink:0;
}
</style>